package com.sph.ga.tool.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.provider.Settings
import java.util.UUID

/** 获取设备唯一标识ID **/
@SuppressLint("HardwareIds")
fun Context.getDeviceUniqueId(): String {
    var deviceUniqueId: String? = null
    var androidId: String? = null
    try {
        val sharedPreferences = getSharedPreferences("device_unique_id", Context.MODE_PRIVATE)
        if (sharedPreferences.contains("device_unique_id"))
            deviceUniqueId = sharedPreferences.getString("device_unique_id", "")
        if (!deviceUniqueId.isNullOrEmpty()) return deviceUniqueId
        androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
    } finally {
        if (androidId.isNullOrEmpty() || "9774d56d682e549c" == androidId)
            androidId = UUID.randomUUID().toString()
        val deviceInfo =
            "$androidId-${Build.HARDWARE}-${Build.BRAND}-${Build.MANUFACTURER}-${Build.PRODUCT}-${Build.FINGERPRINT}-${Build.HOST}-${Build.DISPLAY}"
        deviceUniqueId = UUID.nameUUIDFromBytes(deviceInfo.toByteArray()).toString()
    }
    return deviceUniqueId
}